var express = require("express");
var router = express.Router();
var multiparty = require("multiparty");
const fs = require("fs");
const { promisify } = require("util");

const authMiddleWare = require("../../middleWare/auth");
const { uploadImage } = require("../../utils/common");

// 上传图片到腾讯云cos
router.post("/cos/upload", authMiddleWare, async function (req, res) {
  var multipart = new multiparty.Form();
  multipart.parse(req, async function (err, fields, files) {
    console.log(files, "===");
    let uploadPromises = [];
    files.file.forEach((file) => {
      const uploadPromise = new Promise(async (resolve) => {
        let lastDotIndex = file.originalFilename.lastIndexOf(".");
        let type = file.originalFilename.slice(lastDotIndex + 1);
        let name = file.originalFilename.slice(0, lastDotIndex);
        const readFile = promisify(fs.readFile);
        const fileBuffer = await readFile(file.path);
        let result = await uploadImage(fileBuffer, type, name);
        resolve(result);
      });
      uploadPromises.push(uploadPromise);
    });
    Promise.all(uploadPromises).then((results) => {
      console.log(results, "============29");
      res.send({
        code: 0,
        message: "OK",
        data: results,
      });
    });
  });
});

module.exports = router;
